package com.xlhj.yucloud.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xlhj.yucloud.common.Constants;
import com.xlhj.yucloud.common.ResultData;
import com.xlhj.yucloud.entity.SysRoleInfo;
import com.xlhj.yucloud.entity.SysUserInfo;
import com.xlhj.yucloud.entity.enums.SexEnum;
import com.xlhj.yucloud.entity.enums.StatusEnum;
import com.xlhj.yucloud.service.SysRoleInfoService;
import com.xlhj.yucloud.service.SysUserInfoService;
import com.xlhj.yucloud.service.SysUserRoleService;
import com.xlhj.yucloud.util.SecurityUtils;
import com.xlhj.yucloud.web.model.DictDataInfo;
import com.xlhj.yucloud.web.model.UserInfoReqDto;
import com.xlhj.yucloud.web.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: liucaijing
 * @description: SysUserController
 * @date: 2021/9/18 17:27
 */
@RestController
@RequestMapping("/system/user")
@RequiredArgsConstructor
public class SysUserController {

    private final LoginService loginService;
    private final SysUserInfoService userInfoService;
    private final SysRoleInfoService roleInfoService;
    private final SysUserRoleService userRoleService;

    @GetMapping("/getUserPageList")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public ResultData getUserPageList(UserInfoReqDto reqDto) {
        Page<SysUserInfo> userInfoPage = userInfoService.selectUserInfoPageList(reqDto);
        return ResultData.success().data(userInfoPage);
    }

    @GetMapping("/getUserInfo/{userId}")
    public ResultData getUserInfo(@PathVariable(value = "userId", required = false) Long userId) {
        ResultData resultData = ResultData.success();
        List<SysRoleInfo> roleInfoList = roleInfoService.selectAllRoleInfo();
        if (userId != 0) {
            SysUserInfo userInfo = userInfoService.getById(userId);
            List<Long> roleIds = roleInfoService.selectRoleListByUserId(userId);
            return resultData.data(MapUtil.builder().put("roleIds", roleIds).put("roles", roleInfoList).put("userInfo", userInfo).build());
        }
        return resultData.data(MapUtil.builder().put("roles", roleInfoList).build());
    }

    @PostMapping("/addUser")
    public ResultData addUser(@RequestBody SysUserInfo userInfo) {
        Long count = userInfoService.checkUserNameUnique(userInfo.getUserName());
        if (count.longValue() > 0) {
            return ResultData.error().message("新增用户[" + userInfo.getUserName() + "]失败,用户名已存在!");
        }
        userInfo.setPassword(SecurityUtils.encryptPassword(userInfo.getPassword()));
        userInfo.setAvatar(Constants.AVATAR);
        boolean save = userInfoService.save(userInfo);
        boolean saveBatchUserRole = userRoleService.saveBatchUserRole(userInfo.getId(), userInfo.getRoleIds());
        if (save && saveBatchUserRole) {
            return ResultData.success();
        } else {
            return ResultData.error();
        }
    }

    @PutMapping("/updateUser")
    public ResultData updateUser(@RequestBody SysUserInfo userInfo) {
        if (StringUtils.hasLength(userInfo.getPhonenumber()) && userInfoService.checkPhoneUnique(userInfo.getId(), userInfo.getPhonenumber())) {
            return ResultData.error().message("修改用户[" + userInfo.getUserName() + "]失败,手机号已存在");
        }
        if (StringUtils.hasLength(userInfo.getEmail()) && userInfoService.checkEmailUnique(userInfo.getId(), userInfo.getEmail())) {
            return ResultData.error().message("修改用户[" + userInfo.getUserName() + "]失败,邮箱已存在");
        }
        SysUserInfo info = new SysUserInfo();
        info.setPhonenumber(userInfo.getPhonenumber());
        info.setEmail(userInfo.getEmail());
        info.setSex(userInfo.getSex());
        info.setStatus(userInfo.getStatus());
        info.setId(userInfo.getId());
        boolean update = userInfoService.updateById(info);
        userRoleService.removeByUserId(userInfo.getId());
        boolean saveBatchUserRole = userRoleService.saveBatchUserRole(userInfo.getId(), userInfo.getRoleIds());
        if (update && saveBatchUserRole) {
            return ResultData.success();
        } else {
            return ResultData.error();
        }
    }

    @GetMapping("/getDictInfo/{dictType}")
    public ResultData getDictInfo(@PathVariable("dictType") String dictType) {
        List<DictDataInfo> dataInfoList = new ArrayList<>();
        if (dictType.equals(Constants.DICT_USER_SEX)) {
            SexEnum[] values = SexEnum.values();
            for (SexEnum sex : values) {
                DictDataInfo dataInfo = new DictDataInfo();
                dataInfo.setDictLabel(sex.getDescp());
                dataInfo.setDictValue(sex.getCode());
                dataInfoList.add(dataInfo);
            }
        } else if (dictType.equals(Constants.DICT_USER_STATUS)) {
            StatusEnum[] values = StatusEnum.values();
            for (StatusEnum status : values) {
                DictDataInfo dataInfo = new DictDataInfo();
                dataInfo.setDictLabel(status.getDescp());
                dataInfo.setDictValue(status.getCode());
                dataInfoList.add(dataInfo);
            }
        }
        return ResultData.success().data(dataInfoList);
    }

    @DeleteMapping("/delUserInfo/{userIds}")
    public ResultData delUserInfo(@PathVariable("userIds") Long[] userIds) {
        SysUserInfo userInfo = loginService.getUserInfo();
        Long userId = userInfo.getId();
        if (Arrays.stream(userIds).anyMatch(id -> id.longValue() == userId)) {
            return ResultData.error().message("当前用户不能删除!");
        }
        userInfoService.deleteUserInfoByIds(userIds);
        return ResultData.success();
    }
}
